﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Castle.MicroKernel.Lifestyle;
using Castle.MicroKernel;
using System.Threading;

namespace LifeTree.Core
{
    public class PerWebRequestLifestyleManager : AbstractLifestyleManager
    {
        private string PerRequestObjectID = "PerRequestLifestyleManager_" + Guid.NewGuid().ToString();

        public override object Resolve(CreationContext context)
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items[PerRequestObjectID] == null)
                {
                    HttpContext.Current.Items[PerRequestObjectID] = base.Resolve(context);
                }
                return HttpContext.Current.Items[PerRequestObjectID];
            }
            else 
            {
                LocalDataStoreSlot dataSlot = Thread.GetNamedDataSlot(PerRequestObjectID);
                var obj =  Thread.GetData(dataSlot);
                if (obj != null)
                    return obj;
                obj = base.Resolve(context);
                Thread.SetData(dataSlot, obj);
                return obj;
            }
        }

        public override bool Release(object instance)
        {
            return base.Release(instance);
        }

        public override void Dispose()
        {

        }
    }
}
